﻿using System;
using System.Data;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using MySql.Data.MySqlClient;
using DevExpress.Web.ASPxGridView;
using System.Globalization;

public partial class ReportView_ReportAll : System.Web.UI.Page
{
    private static Common common = new Common();
    private static string strTimeFormat = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.StartDate.Value = DateTime.Now.Date.AddDays(-1).ToString();
            this.EndDate.Value = DateTime.Now.Date.ToString();
            if (Request.QueryString["time"] != null && Request.QueryString["time"].ToString() == "d")
            {
                this.StartDate.Value = DateTime.Now.Date.AddDays(-7).ToString("yyyy/MM/dd HH:mm:ss");
                this.EndDate.Value = DateTime.Now.Date.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (Request.QueryString["connstring"] != null)
            {
                this.hidConnectString.Value = Request.QueryString["connstring"].ToString();//连接字符串
                this.hidProcedure.Value = Request.QueryString["procedure"].ToString();//存储过程名称
                this.hidReportID.Value = Request.QueryString["reportid"].ToString();//报表ID
                this.hidAbscissa.Value = Request.QueryString["x"].ToString();//横坐标名称
                this.hidOrdinate.Value = Request.QueryString["y"].ToString();//纵坐标名称
                this.bLabel.InnerHtml = getChartTitle();
                WebChartControl1.Titles[0].Text = getChartTitle();
                InitGridView(this.hidConnectString.Value, Convert.ToInt32(this.hidReportID.Value.ToString()));
                //InitData();
            }
        }
    }
    protected void btnSelAlarm_Click(object sender, EventArgs e)
    {
        InitData();
    }
    protected void ASPxPageControl1_ActiveTabChanged(object source, DevExpress.Web.ASPxTabControl.TabControlEventArgs e)
    {
        InitData();
    }
    protected void btnXlsExport_Click(object sender, EventArgs e)
    {
        InitData();
		this.gridExport.WriteXlsToResponse();
    }

    #region 统计图操作
    void InitSeries()
    {
        DataSet ds = getDataSet("STAT");//统计图中出现具体详细的信息
        DataTable dt = ds.Tables[0].Copy();//将Dt复制 
        string fieldName = "ne_id";
        string x = this.hidAbscissa.Value;// "new_time_code";
        string y = this.hidOrdinate.Value;// "jietonglv";

        DataTable dt1 = MySQLHelper.SelectDistinct("equip", dt, fieldName);
        DataRow[] dr;
        this.WebChartControl1.Series.Clear();//清除所有的Series
        int length = dt1.Rows.Count;
        int labelLength = 0;
        int n = 0;//记录要存储的节点的循环标记
        string equipName = "";
        for (int i = 0; i < length; i++)
        {
            equipName = dt1.Rows[i][fieldName].ToString();
            dr = dt.Select(fieldName + "='" + equipName + "'");
            equipName = dr[0][1].ToString();//获取设备或指标的名称
            this.WebChartControl1.Series.Add(equipName, GetViewType());
            this.WebChartControl1.Series[equipName].Points.Clear();
            if (i == 0)
            {
                ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels.Clear();
            }
            int num = dr.Length;
            labelLength = num / 3;
            string xAxis = string.Empty;
            for (int j = 0; j < num; j++)
            {
                try
                {
                    try
                    {
                        xAxis = Convert.ToDateTime(dr[j][x].ToString()).ToString(strTimeFormat, DateTimeFormatInfo.InvariantInfo);
                    }
                    catch (Exception)
                    {
                        xAxis = dr[j][x].ToString();
                        //throw;
                    }
                    this.WebChartControl1.Series[equipName].Points.Add(new SeriesPoint(xAxis, dr[j][y]));
                }
                catch (Exception)
                {

                    continue;
                }
                //  if (i == 0 && labelLength > 1 && (((j == 0 || j % labelLength == 0) && (j + labelLength <= num)) || j == num - 1))
                if (labelLength > 0 && i == 0 && (j % labelLength == 0))
                {
                    ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels.Add(new CustomAxisLabel(xAxis));
                    ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels[n++].AxisValue = xAxis;
                }
            }
        }
        if (length == 0)
        {
            this.WebChartControl1.Series.Add("", GetViewType());
        }
        WebChartControl1.Titles[0].Text = getChartTitle();
        string u = GetUnit();
        if (u != string.Empty)
        {
            ((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Text = "单位：" + u;
            ((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Visible = true;
        }
    }
    private string getChartTitle()
    {
        hidUnits.Value = "百分比";
        switch (this.hidReportID.Value.ToString())
        {
            case "101":
                return "网络接通率(TETRA网内)";
            case "102":
                return "排队等待概率";
            case "103":
                return "掉话率";
            case "104":
                return "网络接通率(ISDN)";
            case "105":
                return "发送成功率";
            case "106":
                return "短数据信息丢失率";
            default: return "";
        }
    }
    protected void WebChartControl1_CustomCallback(object sender, DevExpress.XtraCharts.Web.CustomCallbackEventArgs e)
    {
        InitSeries();
        if (e.Parameter == "ViewType")
        {
            PerformViewTypeAction();
        }
        else if (e.Parameter == "ShowLabels")
        {
            PerformViewTypeAction();
            SetSeriesLabel();
        }
    }
    private ViewType GetViewType()
    {
        ViewType v = ViewType.Bar;
        switch ((string)cbViewType.SelectedItem.Text)
        {
            case "曲线图":
                v = ViewType.Line;
                break;
            case "柱状图":
                v = ViewType.Bar;
                break;
            case "饼图":
                v = ViewType.Pie;
                break;
            case "3D饼图":
                v = ViewType.Pie3D;
                break;
        }
        return v;
    }
    void PerformViewTypeAction()
    {
        ViewType viewType = ViewType.Line;
        switch ((string)cbViewType.SelectedItem.Text)
        {
            case "曲线图":
                viewType = ViewType.Line;
                break;
            case "柱状图":
                viewType = ViewType.Bar;
                break;
            case "饼图":
                viewType = ViewType.Pie;
                break;
            case "3D饼图":
                viewType = ViewType.Pie3D;
                break;
        }
        foreach (Series series in WebChartControl1.Series)
        {
            series.ChangeView(viewType);
            byte transparency = 0;
            if (series.View is Area3DSeriesView || series.View is AreaSeriesView || series.View is SplineAreaSeriesView)
                transparency = 135;
            ITransparableView transparableView = series.View as ITransparableView;
            if (transparableView != null)
                transparableView.Transparency = transparency;
            UpdateSeries(series);
        }

        Diagram3D diagram = WebChartControl1.Diagram as Diagram3D;
        if (diagram != null)
        {
            diagram.ZoomPercent = 120;
            XYDiagram3D xyDiagram3D = diagram as XYDiagram3D;
            if (xyDiagram3D != null)
                UpdateAxes(xyDiagram3D.AxisX, xyDiagram3D.AxisY, WebChartControl1.Series[0].View);
        }
        else
        {
            XYDiagram xyDiagram = WebChartControl1.Diagram as XYDiagram;
            if (xyDiagram != null)
                UpdateAxes(xyDiagram.AxisX, xyDiagram.AxisY, WebChartControl1.Series[0].View);
        }
    }
    bool IsFullStackedView(SeriesViewBase view)
    {
        return
            view is FullStackedAreaSeriesView ||
            view is FullStackedArea3DSeriesView ||
            view is FullStackedSplineAreaSeriesView ||
            view is FullStackedSplineArea3DSeriesView;
    }
    void UpdateAxes(AxisBase axisX, AxisBase axisY, SeriesViewBase view)
    {
        axisX.DateTimeOptions.Format = DateTimeFormat.MonthAndDay;
        if (IsFullStackedView(view))
        {
            axisY.NumericOptions.Format = NumericFormat.Percent;
            axisY.NumericOptions.Precision = 0;
        }
        else
            axisY.NumericOptions.Format = NumericFormat.General;
    }
    void UpdateSeries(Series series)
    {
        if (IsFullStackedView(series.View))
        {
            series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
            series.PointOptions.ValueNumericOptions.Precision = 0;
        }
        else
            series.PointOptions.ValueNumericOptions.Format = NumericFormat.General;
    }
    void SetSeriesLabel()
    {
        foreach (Series series in WebChartControl1.Series)
            series.Label.Visible = checkBoxShowLabel.Checked;
    }
    #endregion

    #region 初始化界面
    /// <summary>
    /// 获取指标数据集
    /// </summary>
    /// <param name="conn">数据库连接字符串</param>
    /// <param name="reportid">报表类型ID</param>
    private DataSet GetIndicatorsData(string conn, int reportid)
    {
        CommandType commtype = CommandType.StoredProcedure;
        //存储过程参数
        MySqlParameter[] mySqlPar = new MySqlParameter[1];
        mySqlPar[0] = new MySqlParameter("reporttype", MySqlDbType.Int32);
        mySqlPar[0].Value = reportid;
        //调用函数执行存储过程
        return MySQLHelper.ExecuteDataset(conn, commtype, "report_get_map", mySqlPar);
    }
    private void InitGridView(string conn, int reportid)
    {
        DataSet ds = GetIndicatorsData(conn, reportid);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            int length = ds.Tables[0].Rows.Count;
            GridViewDataTextColumn col1 = new GridViewDataTextColumn();
            col1.FieldName = "equip_name";
            col1.Caption = "设备名称 ";
            Grid.Columns.Add(col1);
            for (int i = 0; i < length; i++)
            {
                GridViewDataTextColumn col = new GridViewDataTextColumn();
                col.FieldName = ds.Tables[0].Rows[i]["EN_TARGET_NAME"].ToString();
                col.Caption = ds.Tables[0].Rows[i]["CN_TARGET_NAME"].ToString();
                if (ds.Tables[0].Rows[i]["DISPLAY_IN_GRAP"].ToString() == "Y")
                {
                    hidUnits.Value += ds.Tables[0].Rows[i]["UNITS"].ToString() + "#";
                }
                col.Caption = ds.Tables[0].Rows[i]["CN_TARGET_NAME"].ToString();
                Grid.Columns.Add(col);
            }
        }
    }
    #endregion

    #region 公共操作
    /// <summary>
    /// 调用存储过程
    /// </summary>
    /// <param name="type">存储过程类型，ALL(返回所有数据),STAT(返回统计值),PARTICULAR(返回详细值)</param>
    /// <returns></returns>
    public DataSet getDataSet(string type)
    {
        //strTimeFormat = common.GetTimeFormat(this.StartDate.Value, this.EndDate.Value);
        //CommandType commtype = CommandType.StoredProcedure;
        ////设置存储过程参数
        //MySqlParameter[] mySqlPar = new MySqlParameter[4];
        //mySqlPar[0] = new MySqlParameter("p_ne_id", MySqlDbType.VarChar);
        //mySqlPar[0].Value = "";// ASPxComboBoxEquipName.SelectedItem.Value;
        //mySqlPar[1] = new MySqlParameter("p_stime", MySqlDbType.DateTime);
        //mySqlPar[1].Value = Convert.ToDateTime(this.StartDate.Value);
        //mySqlPar[2] = new MySqlParameter("p_etime", MySqlDbType.DateTime);
        //mySqlPar[2].Value = Convert.ToDateTime(this.EndDate.Value);
        //mySqlPar[3] = new MySqlParameter("p_is_total", MySqlDbType.VarChar);
        //mySqlPar[3].Value = type.ToUpper();
        ////调用函数执行存储过程
        //DataSet ds = MySQLHelper.ExecuteDataset(this.hidConnectString.Value.Trim(), commtype, this.hidProcedure.Value.Trim(), mySqlPar);
        //return ds;
        string[,] str = new string[4, 2] { { "p_ne_id", "string" }, { "p_stime", "datetime" }, { "p_etime", "datetime" }, { "p_is_total", "string" } };
        string[] v = new string[] { "", this.StartDate.Value, this.EndDate.Value, type.ToUpper() };
        strTimeFormat = common.GetTimeFormat(this.StartDate.Value, this.EndDate.Value);
        return common.GetList(this.hidProcedure.Value.Trim(), str, v);
    }
    //加载数据
    private void InitData()
    {
        if (ASPxPageControl1.ActiveTabIndex == 1)
        {
            this.Grid.DataSource = getDataSet("ALL");//表格中将所有的数据都显示出来
            this.Grid.DataBind();
        }
        else
        {
            InitSeries();
            SetSeriesLabel();
        }
    }
    protected void Grid_PageIndexChanged(object sender, EventArgs e)
    {
        this.Grid.DataSource = getDataSet("ALL");//表格中将所有的数据都显示出来
        this.Grid.DataBind();
    }

    /// <summary>
    /// 转换数据，将数据集列行转换
    /// </summary>
    /// <param name="dt">原数据集</param>
    /// <returns></returns>
    private DataTable ConvertTable(DataTable dt)
    {
        DataTable dtNew = GetTable();
        try
        {
            int rCount = dt.Rows.Count;//行数
            // int cCount = dt.Columns.Count;//列数           

            DataSet ds = GetIndicatorsData(this.hidConnectString.Value.Trim(), Convert.ToInt32(this.hidReportID.Value.Trim()));
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                int length = ds.Tables[0].Rows.Count;
                for (int i = 0; i < length; i++)
                {
                    for (int k = 0; k < rCount; k++)
                    {
                        DataRow dr = dtNew.NewRow();
                        dr[0] = dt.Rows[k][this.hidAbscissa.Value.Trim()].ToString();
                        dr[1] = ds.Tables[0].Rows[i][2].ToString();
                        dr[2] = ds.Tables[0].Rows[i][3].ToString();
                        dr[3] = dt.Rows[k][ds.Tables[0].Rows[i][3].ToString()].ToString();
                        dtNew.Rows.Add(dr);
                    }
                }
            }
        }
        catch (Exception e)
        {

        }
        return dtNew;
    }
    /// <summary>
    /// 创建转换表
    /// </summary>
    /// <returns></returns>
    private DataTable GetTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(this.hidAbscissa.Value.Trim());
        dt.Columns.Add("IndicatorsCN");
        dt.Columns.Add("Indicators");
        dt.Columns.Add("IndicatorsValue");
        return dt;
    }
    private string GetUnit()
    {
        string[] s = hidUnits.Value.Trim().Split('#');
        return s[0];
    }
    #endregion
}
